package com.epam.qanda.mail;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.mail.MessagingException;

import com.epam.qanda.db.model.Category;
import com.epam.qanda.db.model.Question;
import com.epam.qanda.db.model.User;
import com.epam.qanda.db.model.UserCategory;
import com.epam.qanda.db.service.CategoryService;
import com.epam.qanda.db.service.QuestionCategoryService;
import com.epam.qanda.db.service.UserCategoryService;

public class SendingNewQuestion implements Runnable {

	@Override
	public void run() {

		CategoryService categoryService = new CategoryService();
		QuestionCategoryService questionCategoryService = new QuestionCategoryService();
		UserCategoryService userCategoryService = new UserCategoryService();

		int timetoSend = 11;

		Date date = new Date();
		Calendar w = Calendar.getInstance();
		w.setTime(date);

		int h = w.get(Calendar.HOUR_OF_DAY);
		int i = h < timetoSend ? timetoSend - h : 24 - (h - timetoSend);
		try {
			TimeUnit.HOURS.sleep(i);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		while (true) {

			Date aDate = new Date();
			Calendar with = Calendar.getInstance();
			with.setTime(aDate);

			int hour = with.get(Calendar.HOUR_OF_DAY);
			int intDelayInHour = hour < timetoSend ? timetoSend - hour : 24 - (hour - timetoSend);

			List<User> subscribedUsers = userCategoryService.getAllSubscribedUser();
			for (User user : subscribedUsers) {
				StringBuilder message = new StringBuilder();
				message.append("<h2 style=color:red;>" + user.getLogin() + "<h2>" + '\n');
				List<UserCategory> categories = userCategoryService.getUserCategories(user.getId());
				for (UserCategory userCategory : categories) {
					Category cat = categoryService.read(userCategory.getCategoryId());
					message.append("<h4  style=color:blue;>" + cat.getName() + "<h4>" + '\n');
					List<Question> newQuestion = questionCategoryService.getQuestionFor24hByIdCategories(userCategory.getCategoryId());
					for (Question question : newQuestion) {
						message.append("<h5>" + '\t' + question.getText() + '\n' + "<h5>");
					}
				}
				try {
					new EmailUtility().sendEmail("New Questions", message.toString(), user);
				} catch (MessagingException e) {

					e.printStackTrace();
				}

			}

			try {
				TimeUnit.HOURS.sleep(intDelayInHour);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
	}

}
